package com.boot.cloud.sentinel;

import com.alibaba.csp.sentinel.adapter.servlet.CommonFilter;
import com.alibaba.csp.sentinel.adapter.servlet.callback.WebCallbackManager;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;

import javax.servlet.Filter;


/**
 * @author 霜寒 <1621856595@qq.com>
 * @description 所有访问的 URL + HTTP Method 自动统计为 Sentinel 的资源
 * @date 2021/3/25 16:14
 **/
@Configuration
@Import(UrlCleanerImpl.class)
public class SentinelFilterAutoConfiguration implements InitializingBean {

    @Bean
    public FilterRegistrationBean<Filter> sentinelFilterRegistration() {
        FilterRegistrationBean<Filter> registration = new FilterRegistrationBean<>();
        registration.setFilter(new CommonFilter());
        registration.addUrlPatterns("/*");
        registration.setName("sentinelFilter");
        registration.setOrder(1);
        registration.addInitParameter("HTTP_METHOD_SPECIFY", "true");

        return registration;
    }

    @Override
    public void afterPropertiesSet() {
        WebCallbackManager.setUrlCleaner(new UrlCleanerImpl());
    }
}
